<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="RabbitMQ," />










<meta name="description" content="RabbitMQSpringboot-fanout模式广播给所有绑定到当前交换机的队列，分别广播给不同的服务  消费者中不同服务，都会收到生产者发给队列的信息。 生产者模块在pom.xml中引入依赖123456789在pom.xml中引入依赖&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ">
<meta property="og:url" content="https://gitee.com/htt-sub/htt-sub/2023/11/10/RabbitMQ/index.html">
<meta property="og:site_name" content="黄宏涛">
<meta property="og:description" content="RabbitMQSpringboot-fanout模式广播给所有绑定到当前交换机的队列，分别广播给不同的服务  消费者中不同服务，都会收到生产者发给队列的信息。 生产者模块在pom.xml中引入依赖123456789在pom.xml中引入依赖&lt;dependency&gt;    &lt;groupId&gt;org.springframework.boot&lt;&#x2F;groupId&gt;">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/kuangstudy61c5b87b-d787-4d62-9e7c-85e8f26b02f8.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/202307101018179.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/kuangstudy89e09dbc-b6ee-4db6-a6f2-ddbd7b4d95d6.png">
<meta property="og:image" content="c:\Users\ZC\Desktop\Untitled.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111154506261.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111154746890.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111160241664.png">
<meta property="og:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111162902995.png">
<meta property="article:published_time" content="2023-11-10T02:34:41.000Z">
<meta property="article:modified_time" content="2023-11-20T05:53:18.012Z">
<meta property="article:author" content="黄宏涛">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/htt-sub/pic-go/raw/master/images/kuangstudy61c5b87b-d787-4d62-9e7c-85e8f26b02f8.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"post","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/htt-sub/htt-sub/2023/11/10/RabbitMQ/"/>





  <title>RabbitMQ | 黄宏涛</title>
  








<meta name="generator" content="Hexo 6.3.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-post page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">黄宏涛</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/htt-sub/htt-sub/2023/11/10/RabbitMQ/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="黄宏涛">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">RabbitMQ</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2023-11-10T10:34:41+08:00">
                2023-11-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/RabbitMQ/" itemprop="url" rel="index">
                    <span itemprop="name">RabbitMQ</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="RabbitMQ"><a href="#RabbitMQ" class="headerlink" title="RabbitMQ"></a>RabbitMQ</h1><h2 id="Springboot-fanout模式"><a href="#Springboot-fanout模式" class="headerlink" title="Springboot-fanout模式"></a>Springboot-fanout模式</h2><p>广播给所有绑定到当前交换机的队列，分别广播给不同的服务</p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/kuangstudy61c5b87b-d787-4d62-9e7c-85e8f26b02f8.png" alt="img"></p>
<p><span style="color:red">消费者中不同服务，都会收到生产者发给队列的信息。</span></p>
<h3 id="生产者模块"><a href="#生产者模块" class="headerlink" title="生产者模块"></a>生产者模块</h3><h4 id="在pom-xml中引入依赖"><a href="#在pom-xml中引入依赖" class="headerlink" title="在pom.xml中引入依赖"></a>在pom.xml中引入依赖</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">在pom.xml中引入依赖</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<h4 id="在application-yml进行配置"><a href="#在application-yml进行配置" class="headerlink" title="在application.yml进行配置"></a>在application.yml进行配置</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 服务端口</span><br><span class="line">server:</span><br><span class="line">  port: <span class="number">8080</span></span><br><span class="line"># 配置rabbitmq服务</span><br><span class="line">spring:</span><br><span class="line">  rabbitmq:</span><br><span class="line">    username: admin</span><br><span class="line">    password: admin</span><br><span class="line">    virtual-host: /</span><br><span class="line">    host: <span class="number">47.104</span><span class="number">.141</span><span class="number">.27</span></span><br><span class="line">    port: <span class="number">5672</span>     <span class="comment">// 注意端口为5672，不是web页面的15672，易错</span></span><br></pre></td></tr></table></figure>

<h4 id="定义交换机和队列Queue及绑定关系"><a href="#定义交换机和队列Queue及绑定关系" class="headerlink" title="定义交换机和队列Queue及绑定关系"></a>定义交换机和队列Queue及绑定关系</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DirectRabbitMyConfiguration</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 声明fanout模式交换机</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> FanoutExchange <span class="title function_">fanoutExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">FanoutExchange</span>(<span class="string">&quot;fanout模式&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 声明队列</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">smsQueue</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;sms.fanout.queue&quot;</span>,<span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 声明队列</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">duanxinQueue</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;duanxin.fanout.queue&quot;</span>,<span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 完成队列和交换机的绑定关系</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">smsBinding</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">// 绑定sms队列当fanout交换机</span></span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(smsQueue()).to(fanoutExchange());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">duanxinBinding</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">// 绑定sms队列当fanout交换机</span></span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(duanxinQueue()).to(fanoutExchange());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="定义生产者"><a href="#定义生产者" class="headerlink" title="定义生产者"></a>定义生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OrderService</span> &#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">makeOrder</span><span class="params">(String userId,String productId)</span>&#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line">        user.setUserId(<span class="string">&quot;123&quot;</span>);</span><br><span class="line">        user.setAge(<span class="number">24</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;订单生产成功&quot;</span>+user.toString());</span><br><span class="line">        String routingKey=<span class="string">&quot;&quot;</span>;</span><br><span class="line">        <span class="comment">// 参数1 交换机名字，参数2：路由key,参数3 传输内容</span></span><br><span class="line">        <span class="comment">// 发送订单信息给RabbitMQ fanout</span></span><br><span class="line">        rabbitTemplate.convertAndSend(<span class="string">&quot;fanout模式&quot;</span>,routingKey, JSON.toJSONString(user));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">contextLoads</span><span class="params">()</span> &#123;</span><br><span class="line">     orderService.makeOrder(<span class="string">&quot;1&quot;</span>,<span class="string">&quot;6666&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="消费者模块"><a href="#消费者模块" class="headerlink" title="消费者模块"></a>消费者模块</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">在pom.xml中引入依赖</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 服务端口</span><br><span class="line">server:</span><br><span class="line">  port: <span class="number">8081</span></span><br><span class="line"># 配置rabbitmq服务</span><br><span class="line">spring:</span><br><span class="line">  rabbitmq:</span><br><span class="line">    username: admin</span><br><span class="line">    password: admin</span><br><span class="line">    virtual-host: /</span><br><span class="line">    host: <span class="number">47.104</span><span class="number">.141</span><span class="number">.27</span></span><br><span class="line">    port: <span class="number">5672</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;duanxin.fanout.queue&quot;)</span></span><br><span class="line">    <span class="meta">@RabbitHandler</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">reviceMessage</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;短信&quot;</span>+ JSON.parseObject(message, User.class));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;sms.fanout.queue&quot;)</span></span><br><span class="line">    <span class="meta">@RabbitHandler</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">smsMessage</span><span class="params">(String message)</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;sms:&quot;</span>+ JSON.parseObject(message, User.class));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Springboot-Direct模式（点对点）"><a href="#Springboot-Direct模式（点对点）" class="headerlink" title="Springboot-Direct模式（点对点）"></a>Springboot-Direct模式（点对点）</h2><p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/202307101018179.png" alt="img"></p>
<ul>
<li>Direct模式是<strong>fanout模式</strong>上的一种叠加，增加了路由<strong>RoutingKey</strong>的模式,必须是确定的名称，<span style="color:red"><strong>但不能用通配符</strong></span></li>
<li>点对点通信</li>
</ul>
<blockquote>
<p>注意：</p>
</blockquote>
<p><strong>修改队列，一定要在RabbitMQ中删除队列</strong></p>
<p><strong>注意：要先运行生产者，及测试类，才会在RabbitMq中生成对应交换机和队列</strong></p>
<ol>
<li>.with(“queue”);指定路由key</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 更改交换机</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> DirectExchange <span class="title function_">directExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span>  <span class="keyword">new</span> <span class="title class_">DirectExchange</span>(<span class="string">&quot;Direct模式&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">.......</span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">duanxinBinding</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="comment">// 绑定sms队列当fanout交换机</span></span><br><span class="line">    <span class="keyword">return</span> BindingBuilder.bind(duanxinQueue()).to(directExchange()).with(<span class="string">&quot;queue&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>发送信息给rabbitMQ时，指定路由key</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rabbitTemplate.convertAndSend(<span class="string">&quot;Direct模式&quot;</span>,<span class="string">&quot;queue&quot;</span>, JSON.toJSONString(user));</span><br></pre></td></tr></table></figure>

<ol start="3">
<li><strong>修改生产者对应的交互机名称</strong></li>
</ol>
<h2 id="Springboot-Topic模式（广播模式-通配符）"><a href="#Springboot-Topic模式（广播模式-通配符）" class="headerlink" title="Springboot-Topic模式（广播模式+通配符）"></a>Springboot-Topic模式（广播模式+通配符）</h2><p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/kuangstudy89e09dbc-b6ee-4db6-a6f2-ddbd7b4d95d6.png" alt="img"></p>
<p><span style="color:red"><strong>修改队列信息后，要在RabbitMQ中删除原来的队列</strong></span></p>
<ol>
<li>指定路由key，指定通配符</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> TopicExchange <span class="title function_">topicExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">TopicExchange</span>(<span class="string">&quot;Topic模式&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定通配符</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">smsBinding</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">// 绑定sms队列当fanout交换机</span></span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(smsQueue()).to(topicExchange()).with(<span class="string">&quot;*.sms&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">duanxinBinding</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">// 绑定sms队列当fanout交换机</span></span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(duanxinQueue()).to(topicExchange()).with(<span class="string">&quot;queue.#&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>发送信息给rabbitMQ时，<strong>指定路由key，和交换机名称</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rabbitTemplate.convertAndSend(<span class="string">&quot;Topic模式&quot;</span>,<span class="string">&quot;queue.sms&quot;</span>, JSON.toJSONString(user));</span><br></pre></td></tr></table></figure>

<h2 id="过期时间TTL"><a href="#过期时间TTL" class="headerlink" title="过期时间TTL"></a>过期时间TTL</h2><p>过期时间TTL表示可以对消息设置预期的时间，在这个时间内都可以被消费者接收获取；过了之后消息将自动被删除。RabbitMQ可以对<strong>消息和队列</strong>设置TTL。目前有两种方法可以设置。</p>
<ul>
<li>可以通过队列属性设置，队列中的所有消息都有相同的过期时间</li>
<li>可以对消息单独设置，每条TTL可以不同</li>
</ul>
<p>如果上述两种方法同时使用，则<strong>消息的过期时间以两者之间TTL较小的那个数值为准</strong>。消息在队列的生存时间一旦超过设置的TTL值，就称为dead message被投递到死信队列， 消费者将无法再收到该消息。</p>
<ol>
<li><p>队列设置过期时间</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">smsQueus</span><span class="params">()</span>&#123;</span><br><span class="line">        HashMap&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        map.put(<span class="string">&quot;x-message-ttl&quot;</span>,<span class="number">5000</span>); <span class="comment">// 设置过期时间为5秒</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;smsQueue&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,map);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>消息设置过期时间</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">makeOrder</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">MessagePostProcessor</span> <span class="variable">messagePostProcessor</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MessagePostProcessor</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> Message <span class="title function_">postProcessMessage</span><span class="params">(Message message)</span> <span class="keyword">throws</span> AmqpException &#123;</span><br><span class="line">                message.getMessageProperties().setExpiration(<span class="string">&quot;5000&quot;</span>);</span><br><span class="line">                message.getMessageProperties().setContentEncoding(<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> message;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        rabbitTemplate.convertAndSend(MyRabbitMQ.EXAGE_NAME,<span class="string">&quot;&quot;</span>,<span class="string">&quot;你好&quot;</span>,messagePostProcessor);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<h2 id="死信队列"><a href="#死信队列" class="headerlink" title="死信队列"></a>死信队列</h2><p>以下情况会进入死信队列</p>
<ul>
<li>消息被拒绝</li>
<li>消息TTL过期</li>
<li>队列达到最大长度</li>
</ul>
<p><img src="C:\Users\ZC\Desktop\Untitled.png" alt="Untitled"></p>
<p><strong>出现问题,进入死信交换机</strong>(和正常交换机类型一样),进入死信队列</p>
<blockquote>
<p>定义死信交换机和死信队列</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> FanoutExchange <span class="title function_">deadExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">FanoutExchange</span>(DEAD_NAME,<span class="literal">true</span>,<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">deadQueus</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">/* 高版本的RabbitMQ可以用这个配置</span></span><br><span class="line"><span class="comment">        return QueueBuilder.durable(NORMAL_QUEUE).</span></span><br><span class="line"><span class="comment">                // 过期时间, 10000ms=10s</span></span><br><span class="line"><span class="comment">                ttl(10000).  //一般不在这里设置,不灵活,在生产者设置,可以有多个过期时间</span></span><br><span class="line"><span class="comment">                // 连接到死信交换机</span></span><br><span class="line"><span class="comment">                deadLetterExchange(DEAD_EXCHANGE).</span></span><br><span class="line"><span class="comment">                deadLetterRoutingKey(&quot;lisi&quot;)</span></span><br><span class="line"><span class="comment">                .build();*/</span></span><br><span class="line">        HashMap&lt;String, Object&gt; args = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        args.put(<span class="string">&quot;x-message-ttl&quot;</span>,<span class="number">5000</span>); <span class="comment">// 设置过期时间为5秒</span></span><br><span class="line">        args.put(<span class="string">&quot;x-dead-letter-exchange&quot;</span>,“交换机名字”);  <span class="comment">// 不能写为 directExchange()</span></span><br><span class="line">        args.put(<span class="string">&quot;x-dead-letter-routing-key&quot;</span>,<span class="string">&quot;&quot;</span>);</span><br><span class="line">        args.put(<span class="string">&quot;x-max-length&quot;</span>,<span class="number">4</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;deadQueue&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,args);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">deadBinding</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(deadQueus()).to(deadExchange());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>消费者拒绝消息</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@RabbitListener(queues = MyExchange.NORMAL_QUEUE)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">C1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitHandler</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleMessage</span><span class="params">(String message, Channel channel, <span class="meta">@Header(AmqpHeaders.DELIVERY_TAG)</span> <span class="type">long</span> deliveryTag)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 处理消息逻辑</span></span><br><span class="line">            processMessage(message);</span><br><span class="line">            <span class="comment">// 手动ack确认</span></span><br><span class="line">            channel.basicAck(deliveryTag, <span class="literal">false</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="comment">// 手动nack拒绝，并要求重新投递</span></span><br><span class="line">            channel.basicNack(deliveryTag, <span class="literal">false</span>, <span class="literal">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">processMessage</span><span class="params">(String message)</span> &#123;</span><br><span class="line">        <span class="comment">// 模拟处理消息过程</span></span><br><span class="line">        System.out.println(<span class="string">&quot;正在处理消息: &quot;</span> + message);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 抛出异常，模拟处理失败</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;C1拒绝消息,转达死信队列&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="延迟队列"><a href="#延迟队列" class="headerlink" title="延迟队列"></a>延迟队列</h2><p>到达指定时间去处理</p>
<blockquote>
<p>使用场景</p>
</blockquote>
<ol>
<li>订单十分钟之内未支付则自动取消</li>
<li>新创建的店铺,如果十天内没有上传过商品,则自动发送消息提醒</li>
<li>用户注册成功后,三天内没有登陆,则进行短信提醒</li>
<li>用发起退款,如果三天内没有处理,通知运营人员</li>
</ol>
<h2 id="消息确认机制"><a href="#消息确认机制" class="headerlink" title="消息确认机制"></a>消息确认机制</h2><p>Broker：消息代理</p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111154506261.png" alt="image-20231111154506261"></p>
<p><strong>总共三部分的确认机制</strong></p>
<ol>
<li><p><strong>发送端到消息代理</strong> <strong>comfirmCallback</strong></p>
<p>配置文件中开启：publisher-confirms: true &#x2F;&#x2F; <strong>发送端确认</strong></p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111154746890.png" alt="image-20231111154746890"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定制RabbitTemplate</span></span><br><span class="line">    <span class="meta">@PostConstruct</span>   <span class="comment">// MyRabbitMQ对象创建完之后，设置确认回调</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initRabbitTemplate</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">// 设置确认回调</span></span><br><span class="line">        rabbitTemplate.setConfirmCallback(<span class="keyword">new</span> <span class="title class_">RabbitTemplate</span>.ConfirmCallback() &#123;</span><br><span class="line">            <span class="comment">/**  只要消息达到Broker消息代理，ack就返回true，</span></span><br><span class="line"><span class="comment">             *</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> correlationData 当前消息的唯一关联消息,可以设置当前消息的唯一ID</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> ack 消息确认</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> s 异常消息</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">confirm</span><span class="params">(CorrelationData correlationData, <span class="type">boolean</span> ack, String s)</span> &#123;</span><br><span class="line">                System.out.println(correlationData.getId()+<span class="string">&quot;是否收到：&quot;</span>+ack);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// CorrelationData设置消息的ID</span></span><br><span class="line">rabbitTemplate.convertAndSend(MyRabbitMQ.DELAY_NAME,<span class="string">&quot;ss&quot;</span>,<span class="string">&quot;5秒延迟队列发送的消息：你好&quot;</span>,</span><br><span class="line">                <span class="keyword">new</span> <span class="title class_">CorrelationData</span>(UUID.randomUUID().toString()));</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>交换机到队</strong>列 <strong>returnCallback</strong></p>
<p><img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111160241664.png" alt="image-20231111160241664"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">publisher-returns: <span class="literal">true</span></span><br><span class="line"># 只要抵达队列，以异步方式优先回调这个ReturnCofirm</span><br><span class="line">template:</span><br><span class="line">  mandatory: <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置消息的抵达队列的确认回调</span></span><br><span class="line">        rabbitTemplate.setReturnCallback(<span class="keyword">new</span> <span class="title class_">RabbitTemplate</span>.ReturnCallback() &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">/** 只要消息没有投递给指定的队列，就触发这个失败回调，投递失败的详细信息</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> message 投递失败的消息</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> replyCode  回复的状态码</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> replyText  回复的文本内容</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> exchange 发个哪个交换机</span></span><br><span class="line"><span class="comment">             * <span class="doctag">@param</span> routingKey 路由key</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">returnedMessage</span><span class="params">(Message message, <span class="type">int</span> replyCode, String replyText,</span></span><br><span class="line"><span class="params">                                        String exchange, String routingKey)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;Message内容:&quot;</span>+message.getBody()+<span class="string">&quot;Replycode:&quot;</span>+</span><br><span class="line">                        replyCode+<span class="string">&quot;replyText&quot;</span>+replyText+<span class="string">&quot;exchange:&quot;</span>+exchange);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>


</li>
<li><p><strong>队列到消费者</strong> <strong>ack</strong>，保证消息被正确消费，Broker才删除这个消息</p>
</li>
</ol>
<img src="https://gitee.com/htt-sub/pic-go/raw/master/images/image-20231111162902995.png" alt="image-20231111162902995" style="zoom:80%;" />

<p>​			默认是自动确认，消费者收到消息，从队列中删除。</p>
<p>​			自动收消息缺点：自动回复给服务器ack，假如只有一个消息处理成功，宕机了，其余消息会丢失</p>
<blockquote>
<p>手动确认：宕机了，其余消息会变为Ready状态</p>
</blockquote>
<p><span style="color:red">注意：消费者和生产者中的配置文件都需要添加这个，否则报错</span></p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">listener:</span></span><br><span class="line">  <span class="attr">simple:</span></span><br><span class="line">    <span class="attr">acknowledge-mode:</span> <span class="string">manual</span>  <span class="comment"># 手动确认</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;duanxin.fanout.queue&quot;)</span></span><br><span class="line">    <span class="meta">@RabbitHandler</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">reviceMessage</span><span class="params">(String content,Message message, Channel channel)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;短信&quot;</span>+ JSON.parseObject(content, User.class));</span><br><span class="line">        <span class="type">long</span> <span class="variable">deliveryTag</span> <span class="operator">=</span> message.getMessageProperties().getDeliveryTag();</span><br><span class="line">        <span class="keyword">if</span> (deliveryTag%<span class="number">2</span>==<span class="number">0</span>)&#123;</span><br><span class="line">            <span class="comment">// 签收</span></span><br><span class="line">            System.out.println(<span class="string">&quot;签收了：delver&quot;</span>+deliveryTag);</span><br><span class="line">            channel.basicAck(deliveryTag,<span class="literal">false</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 拒收</span></span><br><span class="line">            System.out.println(<span class="string">&quot;拒收了&quot;</span>+deliveryTag);</span><br><span class="line">            <span class="comment">// true表示拒收后是否重新入队</span></span><br><span class="line">            channel.basicNack(deliveryTag,<span class="literal">false</span>,<span class="literal">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>basicAck:用于肯定确认，签收后从队列删除</li>
<li>basicNack: 用于否定确认，可以指定是否批量丢弃，和签收失败是否重新入队</li>
<li>basicReject: 用于否定确认，同上，但不能批量</li>
</ul>
<h2 id="消息丢失、积压、重复"><a href="#消息丢失、积压、重复" class="headerlink" title="消息丢失、积压、重复"></a>消息丢失、积压、重复</h2><blockquote>
<p><strong>消息丢失</strong></p>
</blockquote>
<ol>
<li><p>消息发送出去，由于网络原因没有达到服务器</p>
<ul>
<li><p>使用try-catch，发送消息可能网络失败，失败后要有重试机制，可以记录到数据库，采用定期扫描重发的方式</p>
</li>
<li><p>做好日志记录，每个消息状态是否被服务器收到都应该记录，<strong>保存每一条消息的详细信息</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> IF <span class="keyword">EXISTS</span> `mq_message`;</span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> `mq_message`  (</span><br><span class="line">  `message_id` <span class="type">char</span>(<span class="number">32</span>) <span class="type">CHARACTER</span> <span class="keyword">SET</span> utf8mb4 <span class="keyword">COLLATE</span> utf8mb4_general_ci <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `content` text <span class="type">CHARACTER</span> <span class="keyword">SET</span> utf8mb4 <span class="keyword">COLLATE</span> utf8mb4_general_ci <span class="keyword">NULL</span>,</span><br><span class="line">  `to_exchane` <span class="type">varchar</span>(<span class="number">255</span>) <span class="type">CHARACTER</span> <span class="keyword">SET</span> utf8mb4 <span class="keyword">COLLATE</span> utf8mb4_general_ci <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `routing_key` <span class="type">varchar</span>(<span class="number">255</span>) <span class="type">CHARACTER</span> <span class="keyword">SET</span> utf8mb4 <span class="keyword">COLLATE</span> utf8mb4_general_ci <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `class_type` <span class="type">varchar</span>(<span class="number">255</span>) <span class="type">CHARACTER</span> <span class="keyword">SET</span> utf8mb4 <span class="keyword">COLLATE</span> utf8mb4_general_ci <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `message_status` <span class="type">int</span>(<span class="number">1</span>) <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="number">0</span> COMMENT <span class="string">&#x27;0-新建 1-已发送 2-错误抵达 3-已抵达&#x27;</span>,</span><br><span class="line">  `create_time` datetime <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  `update_time` datetime <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">NULL</span>,</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY (`message_id`) <span class="keyword">USING</span> BTREE</span><br><span class="line">) ENGINE <span class="operator">=</span> InnoDB <span class="type">CHARACTER</span> <span class="keyword">SET</span> <span class="operator">=</span> utf8mb4 <span class="keyword">COLLATE</span> <span class="operator">=</span> utf8mb4_general_ci ROW_FORMAT <span class="operator">=</span> <span class="keyword">Dynamic</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>做好定期重发，如果消息没有发送成功，定期去数据库扫描未成功的消息进行重发</p>
</li>
</ul>
</li>
<li><p>消息抵达Broker，Broker要将消息持久化到磁盘才算成功，此时Broker尚未持久化完成，宕机</p>
<p>publisher必须加入确认回调 </p>
</li>
<li><p>自动ACK状态喜爱，消费者收到消息，但还没来得及消息后宕机</p>
<p>一定要手动ACK，消费成功才会移除。</p>
</li>
</ol>
<p><strong>总结：</strong></p>
<ul>
<li>做好消息确认机制（publisher，consumer手动ACK）</li>
<li>发送的每一个消息都在数据库记录，定期将失败消息重新发送一次</li>
</ul>
<blockquote>
<p>消息重复</p>
</blockquote>
<ol>
<li>消息消费成功，事务已经提交，ACK时，宕机，导致没有ACK成功，Broker消息重新有unack变为Ready，并发送给其它消费者，这个消费者可能重复消费两次。</li>
<li>消息消费失败，由于重试机制，自动将消息又发送出去。</li>
<li>成功消费，ACK宕机，消息由unack变为Ready，Broker又重新发送<ul>
<li>消费者的业务消费接口应该设计为<strong>幂等性</strong>，比如扣库存工作单的状态标志。先进行判断再进行操作</li>
<li>防重表，发送消息每一个有唯一标识，处理过就不处理</li>
<li>rabbitMQ每一个消息都有redelivered字段，可以获取是否被重新投递过来的，而不是第一次投递过来的</li>
</ul>
</li>
</ol>
<blockquote>
<p>消息积压</p>
</blockquote>
<ol>
<li>消费者宕机积压</li>
<li>消费者消费能力不足积压</li>
<li>发送者发送流量太大<ul>
<li>上线更多的消费者</li>
<li>上线专门的队列消费服务，将消息先批量取出来，记录数据库，离线慢慢处理</li>
</ul>
</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/RabbitMQ/" rel="tag"># RabbitMQ</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2023/11/01/%E8%B0%B7%E7%B2%92%E5%95%86%E5%9F%8E/" rel="next" title="谷粒商城">
                <i class="fa fa-chevron-left"></i> 谷粒商城
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#RabbitMQ"><span class="nav-number">1.</span> <span class="nav-text">RabbitMQ</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Springboot-fanout%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.1.</span> <span class="nav-text">Springboot-fanout模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85%E6%A8%A1%E5%9D%97"><span class="nav-number">1.1.1.</span> <span class="nav-text">生产者模块</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%9C%A8pom-xml%E4%B8%AD%E5%BC%95%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">在pom.xml中引入依赖</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%9C%A8application-yml%E8%BF%9B%E8%A1%8C%E9%85%8D%E7%BD%AE"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">在application.yml进行配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89%E4%BA%A4%E6%8D%A2%E6%9C%BA%E5%92%8C%E9%98%9F%E5%88%97Queue%E5%8F%8A%E7%BB%91%E5%AE%9A%E5%85%B3%E7%B3%BB"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">定义交换机和队列Queue及绑定关系</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89%E7%94%9F%E4%BA%A7%E8%80%85"><span class="nav-number">1.1.1.4.</span> <span class="nav-text">定义生产者</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95"><span class="nav-number">1.1.1.5.</span> <span class="nav-text">测试</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B6%88%E8%B4%B9%E8%80%85%E6%A8%A1%E5%9D%97"><span class="nav-number">1.1.2.</span> <span class="nav-text">消费者模块</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Springboot-Direct%E6%A8%A1%E5%BC%8F%EF%BC%88%E7%82%B9%E5%AF%B9%E7%82%B9%EF%BC%89"><span class="nav-number">1.2.</span> <span class="nav-text">Springboot-Direct模式（点对点）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Springboot-Topic%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%B9%BF%E6%92%AD%E6%A8%A1%E5%BC%8F-%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%89"><span class="nav-number">1.3.</span> <span class="nav-text">Springboot-Topic模式（广播模式+通配符）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%87%E6%9C%9F%E6%97%B6%E9%97%B4TTL"><span class="nav-number">1.4.</span> <span class="nav-text">过期时间TTL</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%AD%BB%E4%BF%A1%E9%98%9F%E5%88%97"><span class="nav-number">1.5.</span> <span class="nav-text">死信队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97"><span class="nav-number">1.6.</span> <span class="nav-text">延迟队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E7%A1%AE%E8%AE%A4%E6%9C%BA%E5%88%B6"><span class="nav-number">1.7.</span> <span class="nav-text">消息确认机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E4%B8%A2%E5%A4%B1%E3%80%81%E7%A7%AF%E5%8E%8B%E3%80%81%E9%87%8D%E5%A4%8D"><span class="nav-number">1.8.</span> <span class="nav-text">消息丢失、积压、重复</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">黄宏涛</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
